package juc.mysynchronized;

/**
 * @ClassName ExchangerExample
 * @PackageName juc.mysynchronized
 * @projectName myThread
 * @Description TODO
 * @Author games
 * @Date 2025/9/4 下午4:12
 * @Version 1.0
 */

import java.util.concurrent.Exchanger;

/**
 * 2. Exchanger（数据交换器）
 * 应用场景：
 * <p>
 * 交易场景（一手交钱一手交货），对账场景：用于线程间协作的工具类，用于两个线程间交换数据。
 * 数据交互：在多线程环境中，两个线程可以通过 Exchanger 进行数据交换。
 * 数据采集：在数据采集系统中，可以使用 Exchanger 在采集线程和处理线程间进行数据交换。
 */
public class ExchangerExample {
    private static final Exchanger<String> exchanger = new Exchanger<>();

    public static void main(String[] args) {
        new Thread(() -> {
            try {
                String data1 = "Data from Thread 1";
                System.out.println("Thread 1 is waiting to exchange data.");
                String receivedData = exchanger.exchange(data1);
                System.out.println("Thread 1 received: " + receivedData);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                String data3 = "Data from Thread 3";
                System.out.println("Thread 3 is waiting to exchange data.");
                String receivedData = exchanger.exchange(data3);
                System.out.println("Thread 3 received: " + receivedData);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                String data2 = "Data from Thread 2";
                System.out.println("Thread 2 is waiting to exchange data.");
                String receivedData = exchanger.exchange(data2);
                System.out.println("Thread 2 received: " + receivedData);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}
